import os
from PIL import Image
import piexif


# 定义一个函数来遍历文件夹
def resize_images(directory, max_size_mb=5):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):  # 只处理图片文件
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path) / (1024 * 1024)  # 文件大小转换为MB
                try:
                    # 载入图片
                    with Image.open(file_path) as img:
                        # 读取EXIF信息
                        exif_dict = img.getexif() if 'exif' in img.info else {}
                        # 保存图片，逐步降低质量直到文件大小小于4MB
                        exif_dict['Exif'][41729] = b'1'
                        exif_bytes = piexif.dump(exif_dict)
                        quality = 95  # 初始质量设置
                        while file_size > max_size_mb:
                            # 创建一个临时文件路径，使用Windows系统的路径分隔符
                            temp_file_path = os.path.join(root, 'temp_resize_test.jpg')
                            with open(temp_file_path, 'wb') as f:
                                img.resize((int(img.width / 2), int(img.height / 2)), Image.ANTIALIAS).save(f, 'JPEG', quality=quality, exif=exif_bytes)
                            file_size = os.path.getsize(temp_file_path) / (1024 * 1024)
                            quality -= 5  # 每次降低5的质量
                            # 删除临时文件，如果其不存在则继续
                            if os.path.exists(temp_file_path):
                                os.remove(temp_file_path)

                        # 保存最终调整后的图片，覆盖原文件
                        img.resize((int(img.width / 2), int(img.height / 2)), Image.ANTIALIAS).save(file_path, 'JPEG', quality=quality, exif=exif_bytes)
                        print(f"Resized and saved: {file_path}")
                except Exception as e:
                    print(f"Error processing file {file_path}: {e}")
                    continue  # 继续处理下一个文件

# 调用函数，替换为你的目录
resize_images(r'E:\zdf\pic\XP')
# resize_images(r'E:\zdf\pic\Qp\河口')
# resize_images('pic')